import React, { useState, useRef, useEffect } from 'react';
import { Button, message, Modal } from 'antd';
import { SafetyOutlined, ReloadOutlined, CheckOutlined } from '@ant-design/icons';
import './CaptchaVerification.css';

interface CaptchaVerificationProps {
  onSuccess: () => void;
  onFail: () => void;
  type?: 'slider' | 'click' | 'puzzle';
  difficulty?: 'easy' | 'medium' | 'hard';
}

interface PuzzlePiece {
  id: number;
  x: number;
  y: number;
  correctX: number;
  correctY: number;
  isCorrect: boolean;
}

const CaptchaVerification: React.FC<CaptchaVerificationProps> = ({
  onSuccess,
  onFail,
  type = 'slider',
  // difficulty = 'medium' // 移除未用
}) => {
  const [isVisible, setIsVisible] = useState(false);
  const [verificationType, setVerificationType] = useState(type);
  const [isVerified, setIsVerified] = useState(false);
  const [loading, setLoading] = useState(false);
  
  // 拼图滑块canvas相关状态
  const [bgUrl, setBgUrl] = useState<string>('');
  const [sliderUrl, setSliderUrl] = useState<string>('');
  const [puzzleX, setPuzzleX] = useState(0); // 缺口x
  const [puzzleY, setPuzzleY] = useState(0); // 缺口y
  const [sliderX, setSliderX] = useState(0); // 滑块当前位置
  const [sliderDragging, setSliderDragging] = useState(false);
  const [sliderStatus, setSliderStatus] = useState<'idle'|'success'|'error'>('idle');
  const puzzleSize = 48;
  const bgWidth = 320;
  const bgHeight = 160;
  const sliderRef = useRef<HTMLDivElement>(null);

  // 拼图块路径生成
  function drawPuzzlePath(ctx: CanvasRenderingContext2D, x: number, y: number, size: number, type: 'main' | 'slider') {
    ctx.save();
    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(x + size * 0.3, y);
    ctx.bezierCurveTo(x + size * 0.4, y - size * 0.15, x + size * 0.6, y - size * 0.15, x + size * 0.7, y);
    ctx.lineTo(x + size, y);
    ctx.lineTo(x + size, y + size * 0.3);
    ctx.bezierCurveTo(x + size * 1.15, y + size * 0.4, x + size * 1.15, y + size * 0.6, x + size, y + size * 0.7);
    ctx.lineTo(x + size, y + size);
    ctx.lineTo(x + size * 0.7, y + size);
    ctx.bezierCurveTo(x + size * 0.6, y + size * 1.15, x + size * 0.4, y + size * 1.15, x + size * 0.3, y + size);
    ctx.lineTo(x, y + size);
    ctx.lineTo(x, y + size * 0.7);
    ctx.bezierCurveTo(x - size * 0.15, y + size * 0.6, x - size * 0.15, y + size * 0.4, x, y + size * 0.3);
    ctx.closePath();
    if (type === 'main') {
      ctx.globalCompositeOperation = 'destination-out';
      ctx.fill();
      ctx.globalCompositeOperation = 'source-over';
    } else {
      ctx.clip();
    }
    ctx.restore();
  }

  // 自动生成拼图滑块背景和滑块内容
  function generatePuzzleCaptcha() {
    // 1. 生成背景
    const bgCanvas = document.createElement('canvas');
    bgCanvas.width = bgWidth;
    bgCanvas.height = bgHeight;
    const bgCtx = bgCanvas.getContext('2d')!;
    // 渐变背景
    const grad = bgCtx.createLinearGradient(0, 0, bgWidth, bgHeight);
    grad.addColorStop(0, '#a1c4fd');
    grad.addColorStop(1, '#c2e9fb');
    bgCtx.fillStyle = grad;
    bgCtx.fillRect(0, 0, bgWidth, bgHeight);
    // 加噪声
    for (let i = 0; i < 80; i++) {
      bgCtx.fillStyle = `rgba(59,130,246,${Math.random() * 0.15})`;
      bgCtx.beginPath();
      bgCtx.arc(Math.random() * bgWidth, Math.random() * bgHeight, Math.random() * 18 + 6, 0, 2 * Math.PI);
      bgCtx.fill();
    }
    // 2. 随机缺口位置
    const x = Math.random() * (bgWidth - puzzleSize - 40) + 20;
    const y = Math.random() * (bgHeight - puzzleSize - 40) + 20;
    // 3. 挖缺口
    drawPuzzlePath(bgCtx, x, y, puzzleSize, 'main');
    // 4. 生成滑块内容
    const sliderCanvas = document.createElement('canvas');
    sliderCanvas.width = puzzleSize;
    sliderCanvas.height = puzzleSize;
    const sliderCtx = sliderCanvas.getContext('2d')!;
    sliderCtx.drawImage(bgCanvas, x, y, puzzleSize, puzzleSize, 0, 0, puzzleSize, puzzleSize);
    drawPuzzlePath(sliderCtx, 0, 0, puzzleSize, 'slider');
    // 5. 设置state
    setBgUrl(bgCanvas.toDataURL());
    setSliderUrl(sliderCanvas.toDataURL());
    setPuzzleX(x);
    setPuzzleY(y);
    setSliderX(0);
    setSliderStatus('idle');
  }

  // 初始化拼图滑块
  useEffect(() => {
    if (isVisible && verificationType === 'slider') {
      setTimeout(() => {
        generatePuzzleCaptcha();
      }, 100);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isVisible, verificationType]);

  // 初始化验证器
  const initializeVerification = () => {
    setLoading(true);
    setTimeout(() => {
      switch (verificationType) {
        case 'slider':
          initializeSlider();
          break;
        case 'click':
          initializeClick();
          break;
        case 'puzzle':
          initializePuzzle();
          break;
      }
      setLoading(false);
    }, 300);
  };

  // 初始化滑块验证
  const initializeSlider = () => {
    if (sliderRef.current) {
      const width = sliderRef.current.offsetWidth;
      const target = Math.random() * (width - 60) + 30;
      setSliderX(0);
    }
  };

  // 初始化点击验证
  const initializeClick = () => {
    // 绘制点击验证画布
  };

  // 初始化拼图验证
  const initializePuzzle = () => {
    const pieces: PuzzlePiece[] = [];
    const gridSize = 3;
    const pieceSize = 60;
    
    for (let i = 0; i < gridSize * gridSize; i++) {
      const row = Math.floor(i / gridSize);
      const col = i % gridSize;
      const correctX = col * pieceSize;
      const correctY = row * pieceSize;
      
      pieces.push({
        id: i,
        x: Math.random() * 200,
        y: Math.random() * 200,
        correctX,
        correctY,
        isCorrect: false
      });
    }
    
    // setPuzzlePieces(pieces); // 移除未使用的setPuzzlePieces
  };

  // 滑块拖动逻辑
  const handleSliderDragStart = (e: React.MouseEvent | React.TouchEvent) => {
    setSliderDragging(true);
    document.body.style.userSelect = 'none';
  };
  const handleSliderDrag = (e: MouseEvent | TouchEvent) => {
    if (!sliderDragging) return;
    let clientX = 0;
    if (e instanceof MouseEvent) clientX = e.clientX;
    else if (e.touches && e.touches[0]) clientX = e.touches[0].clientX;
    const track = sliderRef.current;
    if (!track) return;
    const rect = track.getBoundingClientRect();
    let x = clientX - rect.left - puzzleSize / 2;
    x = Math.max(0, Math.min(x, bgWidth - puzzleSize));
    setSliderX(x);
  };
  const handleSliderDragEnd = () => {
    setSliderDragging(false);
    document.body.style.userSelect = '';
    // 判定是否对齐
    if (Math.abs(sliderX - puzzleX) < 8) {
      setSliderX(puzzleX);
      setSliderStatus('success');
      setTimeout(() => {
        handleVerificationSuccess();
        setSliderStatus('idle');
      }, 600);
    } else {
      setSliderStatus('error');
      setTimeout(() => {
        setSliderX(0);
        setSliderStatus('idle');
      }, 400);
      handleVerificationFail();
    }
  };
  // 拖动事件绑定
  useEffect(() => {
    if (!sliderDragging) return;
    const move = (e: MouseEvent | TouchEvent) => handleSliderDrag(e);
    const up = () => handleSliderDragEnd();
    document.addEventListener('mousemove', move);
    document.addEventListener('touchmove', move);
    document.addEventListener('mouseup', up);
    document.addEventListener('touchend', up);
    return () => {
      document.removeEventListener('mousemove', move);
      document.removeEventListener('touchmove', move);
      document.removeEventListener('mouseup', up);
      document.removeEventListener('touchend', up);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sliderDragging, sliderX, puzzleX]);

  // 验证成功处理
  const handleVerificationSuccess = () => {
    setIsVerified(true);
    message.success('验证成功！');
    setTimeout(() => {
      setIsVisible(false);
      onSuccess();
    }, 1000);
  };

  // 验证失败处理
  const handleVerificationFail = () => {
    message.error('验证失败，请重试');
    onFail();
    initializeVerification();
  };

  // 切换验证类型
  const switchVerificationType = (newType: 'slider' | 'click' | 'puzzle') => {
    setVerificationType(newType);
    setIsVerified(false);
  };

  // 重置验证
  const resetVerification = () => {
    setIsVerified(false);
    initializeVerification();
  };

  return (
    <>
      <Button 
        type="primary" 
        icon={<SafetyOutlined />}
        onClick={() => setIsVisible(true)}
        className="captcha-trigger-btn"
      >
        人机验证
      </Button>
      
      <Modal
        title="人机验证"
        open={isVisible}
        onCancel={() => setIsVisible(false)}
        footer={null}
        width={500}
        centered
        className="captcha-modal"
      >
        <div className="captcha-container">
          {/* 验证类型选择 */}
          <div className="verification-type-selector">
            <Button 
              type={verificationType === 'slider' ? 'primary' : 'default'}
              onClick={() => switchVerificationType('slider')}
              size="small"
            >
              滑块验证
            </Button>
          </div>

          {/* 验证区域 */}
          <div className="verification-area">
            {loading ? (
              <div className="loading-area">
                <div className="loading-spinner"></div>
                <p>正在加载验证...</p>
              </div>
            ) : (
              <>
                {/* 滑块验证 */}
                {verificationType === 'slider' && (
                  <div className="slider-verification">
                    <div
                      className="puzzle-bg-container"
                      ref={sliderRef} // 轨道容器ref
                      style={{position:'relative',width:bgWidth,height:bgHeight,margin:'0 auto'}}
                    >
                      {bgUrl && <img src={bgUrl} alt="bg" style={{width:bgWidth,height:bgHeight,borderRadius:12,boxShadow:'0 2px 12px rgba(59,130,246,0.08)'}} />}
                      {/* 缺口阴影 */}
                      <canvas
                        width={puzzleSize}
                        height={puzzleSize}
                        style={{position:'absolute',top:puzzleY,left:puzzleX,opacity:0.18,pointerEvents:'none'}}
                        ref={el => {
                          if (el && bgUrl) {
                            const ctx = el.getContext('2d');
                            if (ctx) {
                              ctx.clearRect(0,0,puzzleSize,puzzleSize);
                              drawPuzzlePath(ctx,0,0,puzzleSize,'slider');
                              ctx.fillStyle = '#000';
                              ctx.globalAlpha = 0.5;
                              ctx.fill();
                              ctx.globalAlpha = 1;
                            }
                          }
                        }}
                      />
                      {/* 滑块 */}
                      {sliderUrl && (
                        <div
                          className={`puzzle-slider ${sliderStatus}`}
                          style={{
                            position:'absolute',
                            top:puzzleY,
                            left:sliderX,
                            width:puzzleSize,
                            height:puzzleSize,
                            cursor:sliderDragging?'grabbing':'grab',
                            zIndex:10,
                            transition:sliderStatus==='success'? 'left 0.5s cubic-bezier(.4,2,.6,1)' : sliderStatus==='error'? 'left 0.3s cubic-bezier(.4,0,.2,1)' : 'none',
                            boxShadow:'0 4px 16px rgba(59,130,246,0.18)',
                            borderRadius:10,
                            background:'#fff',
                            display:'flex',alignItems:'center',justifyContent:'center',
                            userSelect:'none',
                            pointerEvents:'auto',
                          }}
                          onMouseDown={e => { e.preventDefault(); handleSliderDragStart(e); }}
                          onTouchStart={e => { e.preventDefault(); handleSliderDragStart(e); }}
                        >
                          <img src={sliderUrl} alt="slider" style={{width:puzzleSize,height:puzzleSize,borderRadius:10,pointerEvents:'none'}} />
                        </div>
                      )}
                    </div>
                    <p className="verification-tip">{sliderStatus === 'success' ? '验证通过' : sliderStatus === 'error' ? '验证失败，请重试' : sliderDragging ? '松开验证' : '请将滑块拼图拖到缺口处'}</p>
                  </div>
                )}
              </>
            )}
          </div>

          {/* 操作按钮 */}
          <div className="verification-actions">
            <Button 
              icon={<ReloadOutlined />}
              onClick={resetVerification}
              disabled={loading}
            >
              重新验证
            </Button>
            <Button 
              type="primary"
              icon={<CheckOutlined />}
              disabled={!isVerified}
              onClick={() => setIsVisible(false)}
            >
              确认
            </Button>
          </div>
        </div>
      </Modal>
    </>
  );
};

export default CaptchaVerification; 